package com.wutianyi.interesting;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;


/**
 * @author hanjie.wuhj 
 * 文件排序 
 * 文件中每行保存一个数字
 * 数字没有重复的
 * 没有其他相关的信息与数字想关联 
 * 大概只有1M的内存空间可以使用
 */
public class FileSort {

	/**
	 * 1MB的内存
	 */
	byte[] results = new byte[1024 * 1024];
	byte[] values = new byte[] { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, -128 };

	void createSortFile(String file) {
		PrintWriter pw = null;
		try {
			pw = new PrintWriter(new File(file));
			int value = 1024 * 1024 * 8 - 1;
			for (int i = value; i >= 0; i--) {
				pw.println(i);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (null != pw) {
				pw.close();
			}
		}

	}

	void sortFile(String file) {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(
					new FileInputStream(file)));

			String line = reader.readLine();
			while (null != line && !line.isEmpty()) {
				int v = Integer.parseInt(line);
				dealValue(v);
				line = reader.readLine();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != reader) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	void dealValue(int v) {
		int index = v / 8;
		int position = v % 8;

		results[index] = (byte) (results[index] | values[position]);

	}

	void printValue(String out) {
		PrintWriter pw = null;
		try {
			pw = new PrintWriter(new File(out));
			int i = 0;
			int index = 1;
			for (byte result : results) {
				for (int j = 0; j < 8; j++) {
					if ((result & values[j]) == values[j]) {
						pw.println(i + j);
					}
				}
				i = index * 8;
				++index;
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (null != pw) {
				pw.flush();
				pw.close();
			}
		}
	}

	public static void main(String[] args) {
		FileSort sort = new FileSort();
//		sort.createSortFile("sort=original.txt");
		long start = System.currentTimeMillis();
		sort.sortFile("sort=original.txt");
		long end_1 = System.currentTimeMillis();
		System.out.println("sort time: " + (end_1 - start));
		sort.printValue("sort-result.txt");
		long end_2 = System.currentTimeMillis();
		System.out.println("writer file time: " + (end_2 - end_1));
	}
}
